package com.winz.cultureapp.fragment;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.terry.zxing.zxing.android.CaptureActivity;
import com.winz.cultureapp.R;
import com.winz.cultureapp.activity.AdminActivity;
import com.winz.cultureapp.activity.AdminActivityOrderActivity;
import com.winz.cultureapp.activity.AdminStadiumOrderActivity;
import com.winz.cultureapp.activity.CertificationActivity;
import com.winz.cultureapp.activity.CodeActivity;
import com.winz.cultureapp.activity.CollectionActivity;
import com.winz.cultureapp.activity.LoginActivity;
import com.winz.cultureapp.activity.MessageActivity;
import com.winz.cultureapp.activity.PersonalRecordActivity;
import com.winz.cultureapp.activity.UserInfoActivity;
import com.winz.cultureapp.application.DemoApplication;
import com.winz.cultureapp.base.BaseFragment;
import com.winz.cultureapp.constants.Constants;
import com.winz.cultureapp.entity.ActivityBookDetailBean;
import com.winz.cultureapp.entity.AdminBookDetailBean;
import com.winz.cultureapp.entity.BookFixBean;
import com.winz.cultureapp.entity.UserChangPwdBean;
import com.winz.cultureapp.http.OnResponeListener;
import com.winz.cultureapp.http.request.AdminBookDetailReq;
import com.winz.cultureapp.http.request.ChangPwdReq;
import com.winz.cultureapp.http.request.RequestFactory;
import com.winz.cultureapp.http.util.HttpUitls;
import com.winz.cultureapp.utils.JsonUtil;
import com.winz.cultureapp.utils.Logger;
import com.winz.cultureapp.utils.SharePrefsUtil;
import com.winz.cultureapp.widge.ChangPwdDialog;

import java.io.File;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 我的
 */
public class MineFragment extends BaseFragment {
    private final static int REQUEST_CODE_SCAN = 0X000001;
    private static final String DECODED_CONTENT_KEY = "codedContent";
    private static final String PERMISSION_WRITE_STORAGE = Manifest.permission.WRITE_EXTERNAL_STORAGE;
    private static final String PERMISSION_CAMERA = Manifest.permission.CAMERA;
    private static final int REQUEST_PERMISSION_CODE = 267;
    @BindView(R.id.view_root)
    View view;
    @BindView(R.id.tv_login)
    TextView mTv_login;
    @BindView(R.id.iv_header)
    ImageView mIv_header;
    @BindView(R.id.ll_item6)
    LinearLayout mLl_item6;
    @BindView(R.id.tv_tip)
    TextView mTv_user;

    private String qrCoded;

    private PopupWindow pop = null;
    private LinearLayout ll_popup;
    private GetPictureFragment getPicture;
    private GetPictureFragment.OnGetPictureListener mOnGetPictureListener = new GetPictureFragment.OnGetPictureListener() {

        @Override
        public void onComplete(String result) {
            try {
                getPicture.dismiss();
                upLoadHeader(result);

            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        @Override
        public void onCancel() {
            getPicture.dismiss();
        }
    };

    public static MineFragment getInstance() {
        MineFragment fragment = new MineFragment();
        return fragment;
    }

    @Override
    protected int contentView() {
        return R.layout.fragment_mine;
    }

    @Override
    protected void initViews(View view) {
        iniPop();
    }
    private void iniPop() {
        pop = new PopupWindow(mContext);

        View view = getLayoutInflater().inflate(R.layout.item_popupwindows, null);

        ll_popup = (LinearLayout) view.findViewById(R.id.ll_popup);

        pop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        pop.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        pop.setBackgroundDrawable(new BitmapDrawable());
        pop.setFocusable(true);
        pop.setOutsideTouchable(true);
        pop.setContentView(view);

        RelativeLayout parent = (RelativeLayout) view.findViewById(R.id.parent);
        Button bt1 = (Button) view
                .findViewById(R.id.item_popupwindows_camera);
        Button bt2 = (Button) view
                .findViewById(R.id.item_popupwindows_Photo);
        Button bt3 = (Button) view
                .findViewById(R.id.item_popupwindows_cancel);
        parent.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                pop.dismiss();
                ll_popup.clearAnimation();
            }
        });
        bt1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                //检查是否获得写入权限，未获得则向用户请求
                if (ActivityCompat.checkSelfPermission(mContext, PERMISSION_CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    //未获得，向用户请求
                    Log.d("Register", "无读写权限，开始请求权限。");
                    ActivityCompat.requestPermissions(mContext, new String[]
                            {PERMISSION_CAMERA, PERMISSION_WRITE_STORAGE}, REQUEST_PERMISSION_CODE);
                } else {
                    Log.d("Register", "有读写权限，准备启动相机。");
                    photo();
                }

                pop.dismiss();
                ll_popup.clearAnimation();
            }
        });
        bt2.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                /**
                 * 打开相册
                 */
                openAlbum();
                pop.dismiss();
                ll_popup.clearAnimation();
            }
        });
        bt3.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                pop.dismiss();
                ll_popup.clearAnimation();
            }
        });
    }
    @Override
    protected void loadDatas() {

        if (!TextUtils.isEmpty(SharePrefsUtil.getInstance().getString(Constants.USER_INFO.TOKEN))){
            DemoApplication.getInstance().isLogin = true;
            mTv_user.setText(SharePrefsUtil.getInstance().getString(Constants.USER_INFO.USER_NAME,"默认用户"));
            String head_image = SharePrefsUtil.getInstance().getString(Constants.USER_INFO.HEAD_IMAGE,"");
            Glide.with(mContext)
                    .load(head_image)
                    .error(R.drawable.test_heaer_nor)
                    .into(mIv_header);
            mIv_header.setVisibility(View.VISIBLE);
            mTv_login.setVisibility(View.GONE);
            if (SharePrefsUtil.getInstance().getBoolean(Constants.USER_INFO.ISADMIN)){
                mLl_item6.setVisibility(View.VISIBLE);
            }else {
                mLl_item6.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 拍照
     */
    private void photo() {
        //启动照相机
        getPicture = GetPictureFragment.newInstance(GetPictureFragment.TYPE_REGIST, 200, 200, true);
        getPicture.setOnGetPictureListener(mOnGetPictureListener);
        getPicture.show(getActivity().getSupportFragmentManager(), "tag");
//        getPicture.setIsNeed(false);


    }

    /**
     * 打开相册
     */
    private void openAlbum() {
        getPicture = GetPictureFragment.newInstance(GetPictureFragment.TYPE_REGIST, 200, 200, false);
        getPicture.setOnGetPictureListener(mOnGetPictureListener);
        getPicture.show(getActivity().getSupportFragmentManager(), "tag");
//        getPicture.setIsNeed(false);
    }

    /**
     * 返回用户是否允许权限的结果，并处理
     */
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResult) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResult);
        if (requestCode == REQUEST_PERMISSION_CODE) {
            if (grantResult.length > 0 && grantResult[0] == PackageManager.PERMISSION_GRANTED) {
                // 用户允许
                Logger.i("Register", "用户已允许权限，准备启动相机。");
                //启动照相机
                photo();
            } else {
                //用户拒绝
                Logger.i("Register", "用户已拒绝权限，程序终止。");
                showMsg("您拒绝本应用使用相机，请在设置权限中允许使用相机功能！！！！");
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        loadDatas();
    }

    @OnClick({R.id.tv_login,
            R.id.iv_header,
            R.id.ll_approve, R.id.ll_scan, R.id.ll_collection, R.id.ll_msg,
            R.id.ll_item1, R.id.ll_item2, R.id.ll_item3, R.id.ll_item4, R.id.ll_item5, R.id.ll_item6, R.id.ll_item7,R.id.ll_item8})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_login:
                startActivity(LoginActivity.class,false);
                break;
            case R.id.iv_header:
                // 更换头像
                ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.activity_translate_in));
                pop.showAtLocation(view, Gravity.BOTTOM, 0, 0);
                break;
            case R.id.ll_approve: // 我的认证
                if (DemoApplication.getInstance().isLogin){
                    startActivity(CertificationActivity.class, false);
                }else {
                    showMsg("请先登录");
                }
                break;
            case R.id.ll_scan:
                // 扫一扫
                Intent intent = new Intent(mContext, CaptureActivity.class);
                startActivityForResult(intent, REQUEST_CODE_SCAN);
                break;
            case R.id.ll_collection: // 我的收藏
                if (DemoApplication.getInstance().isLogin){
                    startActivity(CollectionActivity.class, false);
                }else {
                    showMsg("请先登录");
                }
                break;
            case R.id.ll_msg: // 我的消息
                if (DemoApplication.getInstance().isLogin){
                    startActivity(MessageActivity.class, false);
                }else {
                    showMsg("请先登录");
                }
                break;
            case R.id.ll_item1: // 个人信息
                if (DemoApplication.getInstance().isLogin){
                    startActivity(UserInfoActivity.class, false);
                }else {
                    showMsg("请先登录");
                }
                break;
            case R.id.ll_item2: // 个人记录
                if (DemoApplication.getInstance().isLogin){
                    startActivity(PersonalRecordActivity.class, false);
                }else {
                    showMsg("请先登录");
                }

                break;
            case R.id.ll_item5: // 密码修改
                if (DemoApplication.getInstance().isLogin){
                    final ChangPwdDialog dialog = new ChangPwdDialog(mContext);
                    dialog.setOkButtonOnClickListener(new ChangPwdDialog.OkButtonOnClickListener() {
                        @Override
                        public void onFinished(Map<String, String> data) {
                            if (isAllright(data)) {
                                changePwd(data);
                                dialog.dismiss();
                            }
                        }
                    });
                }else {
                    showMsg("请先登录");
                }
                break;
            case R.id.ll_item6:
                if (DemoApplication.getInstance().isLogin){
                    startActivity(AdminActivity.class, false);
                }else {
                    showMsg("请先登录");
                }

                break;
            case R.id.ll_item7:
                loginOut();
                break;
            case R.id.ll_item8:
                startActivity(CodeActivity.class,false);
                break;
        }
    }

    private boolean isAllright(Map<String, String> data) {
        if (TextUtils.isEmpty(data.get("old"))) {
            showMsg("请输入原密码");
            return false;
        }
        if (TextUtils.isEmpty(data.get("new"))) {
            showMsg("请输入新密码");
            return false;
        }
        if (TextUtils.isEmpty(data.get("new"))) {
            showMsg("请输入新密码");
            return false;
        }
        return true;
    }

    /**
     * 修改密码
     */
    private void changePwd(Map<String, String> data) {
        showProgressDialog();
        HttpUitls.onPostByToken("user_password_update", SharePrefsUtil.getInstance().getString(Constants.USER_INFO.TOKEN), new ChangPwdReq(data.get("again"),data.get("new"),data.get("old")), new OnResponeListener<UserChangPwdBean>() {
            @Override
            public void onSuccess(UserChangPwdBean bean) {
                Logger.d("user_password_update==>>", JsonUtil.getJsonFromObj(bean));
                if (bean.code == 0) {
                    showMsg(bean.msg);
                    loginOut();
                }else{
                    showMsg(bean.msg);
                }
                dismissProgressDialog();
            }

            @Override
            public void onFailed(String error) {
                Logger.d("user_password_update==>>", error);
                dismissProgressDialog();
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 扫描二维码/条码回传
        if (requestCode == REQUEST_CODE_SCAN && resultCode == mContext.RESULT_OK) {
            if (data != null) {
                String content = data.getStringExtra(DECODED_CONTENT_KEY);
                qrCoded = content;

                String flag = qrCoded.substring(qrCoded.indexOf("flag=")+5,qrCoded.indexOf("flag=")+6);
                String value = qrCoded.substring(qrCoded.lastIndexOf("str=")+4,qrCoded.length());
                switch (flag){
                    case "0":
                        // 活动订单详情
                        checkActivity(value);
                        break;
                    case "1":
                        // 场馆订单详情
                        checkStadium(value);
                        break;
                    default:
                        showMsg("未知类型");

                }
            }
        }
    }


    /**
     * 更新UI
     */
    private void updateUi() {
        mTv_user.setText(SharePrefsUtil.getInstance().getString(Constants.USER_INFO.USER_NAME,"默认用户"));
        String head_image = SharePrefsUtil.getInstance().getString(Constants.USER_INFO.HEAD_IMAGE,"");
        Glide.with(mContext)
                .load(head_image)
                .error(R.drawable.test_heaer_nor)
                .into(mIv_header);
    }


    private void loginOut() {

        AlertDialog.Builder versionDialog = new AlertDialog.Builder(mContext, AlertDialog.THEME_HOLO_LIGHT);
        versionDialog.setMessage("确定退出当前用户吗？");
        versionDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 清空数据
                SharePrefsUtil.getInstance().delectedUserInfo();
                updateUi();
                mIv_header.setVisibility(View.GONE);
                mTv_login.setVisibility(View.VISIBLE);
                loadDatas();
                dialog.dismiss();
            }
        });
        versionDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        if (versionDialog != null) {
            versionDialog.show();
        }


    }

    private void checkActivity(String randomstr) {
        showProgressDialog();
        HttpUitls.onPostByToken("admin_user_activity_book_detail", SharePrefsUtil.getInstance().getString(Constants.USER_INFO.TOKEN), new AdminBookDetailReq(randomstr), new OnResponeListener<ActivityBookDetailBean>() {
            @Override
            public void onSuccess(ActivityBookDetailBean bean) {
                Logger.d("admin_user_activity_book_detail==>>", JsonUtil.getJsonFromObj(bean));
                if (bean.code == 0) {
                    if (bean.data.useStatus == 0){
                        // 未使用
                        Bundle bundle = new Bundle();
                        bundle.putSerializable(Constants.KEY.ADMIN.DETAIL,bean.data);
                        bundle.putString(Constants.KEY.ADMIN.RANDOMSTR,randomstr);
                        startActivity(AdminActivityOrderActivity.class,false,bundle);
                    }else {
                        showMsg(bean.data.useStatus==1?"已使用":"已过期");
                    }

                }else{
                    showMsg(bean.msg);
                }
                dismissProgressDialog();
            }

            @Override
            public void onFailed(String error) {
                Logger.d("admin_user_activity_book_detail==>>", error);
                dismissProgressDialog();
            }
        });
    }

    private void checkStadium(String randomstr) {
        showProgressDialog();
        HttpUitls.onPostByToken("admin_user_unit_book_detail", SharePrefsUtil.getInstance().getString(Constants.USER_INFO.TOKEN), new AdminBookDetailReq(randomstr), new OnResponeListener<AdminBookDetailBean>() {
            @Override
            public void onSuccess(AdminBookDetailBean bean) {
                Logger.d("admin_user_unit_book_detail==>>", JsonUtil.getJsonFromObj(bean));
                if (bean.code == 0) {
                    if (bean.data.useStatus == 0){
                        // 未使用
                        Bundle bundle = new Bundle();
                        bundle.putSerializable(Constants.KEY.ADMIN.DETAIL,bean.data);
                        bundle.putString(Constants.KEY.ADMIN.RANDOMSTR,randomstr);
                        startActivity(AdminStadiumOrderActivity.class,false,bundle);
                    }else {
                        showMsg(bean.data.useStatus==1?"已使用":"已过期");
                    }

                }else{
                    showMsg(bean.msg);
                }
                dismissProgressDialog();
            }

            @Override
            public void onFailed(String error) {
                Logger.d("admin_user_unit_book_detail==>>", error);
                dismissProgressDialog();
            }
        });
    }

    /**
     * 上传头像
     */
    private void upLoadHeader(String url) {
        showProgressDialog();
        HttpUitls.onPostByToken("user_headerimage",
                SharePrefsUtil.getInstance().getString(Constants.USER_INFO.TOKEN),
                RequestFactory.getInstance().user_headerimage(new File(url)), new OnResponeListener<BookFixBean>() {
            @Override
            public void onSuccess(BookFixBean bean) {
                Logger.d("user_headerimage==>>", JsonUtil.getJsonFromObj(bean));
                if (bean.code == 0) {
                    showMsg("修改成功");
                    SharePrefsUtil.getInstance().putString(Constants.USER_INFO.HEAD_IMAGE,bean.data.headerImage);
                    updateUi();
                }else{
                    showMsg(bean.msg);
                }
                dismissProgressDialog();
            }

            @Override
            public void onFailed(String error) {
                Logger.d("user_headerimage==>>", error);
                dismissProgressDialog();
            }
        });
    }

}
